/**
 * [748] 最短补全词
 *
 * @format
 * @lc app=leetcode.cn id=748 lang=javascript
 */

// @lc code=start
/**
 * @param {string} licensePlate
 * @param {string[]} words
 * @return {string}
 */
var shortestCompletingWord = function (licensePlate, words) {
    // const isletter = (char) => (char >= "a" && char <= "z") || (char >= "A" && char <= "Z")
    // 字母检测
    const isletter = RegExp.prototype.test.bind(/[a-z]/i)
    let str = licensePlate.toLowerCase()
    // console.log(str, words)
    let char = ""
    // 获取正则字典
    const dist = {}
    for (let i = 0; i < str.length; i++) {
        char = str[i]
        if (isletter(char)) dist[char] ? dist[char]++ : (dist[char] = 1)
    }
    // console.log(dist)
    // 构造最短补全词正则
    str = ""
    for (let key in dist) {
        char = ""
        for (let i = 0; i < dist[key]; i++) {
            char += `.*${key}`
        }
        char = `(?=${char}.*)`
        str += char
    }
    // console.log(str)
    const isComplete = RegExp.prototype.test.bind(RegExp(str))
    let result = ""
    for (let i = 0; i < words.length; i++) {
        if (result) {
            isComplete(words[i]) && words[i].length < result.length ? (result = words[i]) : null
        } else {
            isComplete(words[i]) ? (result = words[i]) : null
        }
    }
    return result
}
debugger
// console.log(shortestCompletingWord("1s3 PSt", ["step", "steps", "stripe", "stepple"]))
// @lc code=end
